var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var { ForbiddenError, ServiceError, UnKnowError } = require('./utils/errors')

require('express-async-errors')

// 引入数据库连接
require('./dao/dbConnection')
// 默认读取项目根目录下的 .env环境变量文件
require('dotenv').config()

var webRouter = require('./routes/webRouter');
var adminRouter = require('./routes/adminRouter');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/web', webRouter);
app.use('/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  console.log('===============>> err', err);
  if (err.name === 'UnauthorizedError') {
    res.send(new ForbiddenError('未登录，或登录已过期').toResponseJson())
  } else if (err instanceof ServiceError) {
    res.send(err.toResponseJson())
  } else {
    res.send(new UnKnowError('未知错误'))
  }
});

module.exports = app;
